package tool

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/thedevsaddam/gojsonq/v2"
)

const (
	code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	appID           = ""
	appSecret       = ""
)

// 获取微信open_id
func GetOpenId(c *gin.Context) any {

	//获取code
	code := c.PostForm("code")

	//调用auth.code2Session接口获取openid
	url := fmt.Sprintf(code2sessionURL, appID, appSecret, code)
	resp, err := http.Get(url)
	if err != nil {
		log.Println(err)
		return nil
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	json := gojsonq.New().FromString(string(body)).Find("openid")
	openId, ok := json.(string)
	if !ok {
		return nil
	}
	fmt.Println("my openid is: ", openId)
	return openId

}
